package com.smartfast4j.manager.modules.sys.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.smartfast4j.common.Constants;
import com.smartfast4j.common.annotation.LogRecord;
import com.smartfast4j.common.annotation.PermissionLimit;
import com.smartfast4j.common.bean.R;
import com.smartfast4j.common.util.ConversionUtil;
import com.smartfast4j.manager.common.controller.ManagerBaseController;
import com.smartfast4j.manager.modules.sys.bean.SysUserExt;
import com.smartfast4j.manager.modules.sys.service.SysUserRoleService;
import com.smartfast4j.manager.modules.sys.service.SysUserService;
import com.smartfast4j.pojo.sys.SysUser;
import com.smartfast4j.pojo.sys.SysUserExample;
import com.smartfast4j.pojo.sys.SysUserRole;
import com.smartfast4j.pojo.sys.SysUserRoleExample;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* SysUserController
*  由代码生成器生成
*/
@PermissionLimit //在类上标注了@PermissionLimit注解后这个类下的所有接口都需要做访问权限控制
@RestController
@RequestMapping("/sysUser")
public class SysUserController extends ManagerBaseController {

    @Autowired
    private SysUserService sysUserService;


    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 新增系统用户
     *
     */
    @LogRecord(operation="新增用户",remark = "新增系统用户",moduleName = "用户管理")//使用自定义的LogRecord注解记录操作日志
    @RequestMapping(value = "/add")
    public R add(SysUserExt sysUser) {
        sysUser.setCreateUser(getLoginUserId());//创建人的用户ID
        sysUser.setUpdateUser(getLoginUserId());//最近一次修改的用户ID
        sysUserService.save(sysUser);
        return R.ok().msg("创建成功！");
    }

    /**
     * 获取系统用户列表
     * @return
     */
    @RequestMapping(value = "/list")
    public R list(Integer offset, Integer limit,SysUser user) {
        if (offset != null && limit != null) {
            //分页查询
            PageHelper.offsetPage(offset, limit);
        }
        SysUserExample example = new SysUserExample();
        SysUserExample.Criteria criteria = example.createCriteria();
        criteria.andDeleteFlagEqualTo(Constants.DELETE_FLAG.NO);
        //只有超级管理员，才能查看所有管理员列表，如果不是超级管理员，只能看到自己创建的管理员用户列表
        if (!getLoginUserRoleIds().contains(Constants.SUPER_ADMIN)) {
            criteria.andCreateUserEqualTo(getLoginUserId());
        }
        if(StringUtils.isNotEmpty(user.getUsername())){
            criteria.andUsernameLike("%"+user.getUsername()+"%");
        }
        if(StringUtils.isNotBlank(user.getRealName())){
            criteria.andRealNameLike("%" + user.getRealName() + "%");
        }
        if(StringUtils.isNotBlank(user.getCellphone())){
            criteria.andCellphoneLike("%" + user.getCellphone() + "%");
        }
        example.setOrderByClause("create_time desc, update_time desc");
        //只有紧跟在 PageHelper.startPage 方法后的第一个 MyBatis 的查询(select)方法会被分页。
        List<SysUser> sysUserList = sysUserService.selectByExample(example);
        PageInfo<SysUser> pageInfo = new PageInfo<>(sysUserList);

        //需要返回的数据集合
        List<Map<String,Object>> resultList = new ArrayList<>();

        for (SysUser sysUser : sysUserList){
            //bean转成Map
            Map<String,Object> map = ConversionUtil.beanToMap(sysUser);
            SysUser updateUser = sysUserService.getSysUser(sysUser.getUpdateUser());
            SysUser createUser = sysUserService.getSysUser(sysUser.getCreateUser());
            if(ConversionUtil.isNotEmptyParameter(updateUser)){
                //添加额外字段返回
                map.put("createUser",createUser.getRealName());//创建人
                map.put("updateUser",updateUser.getRealName());//更新人
            }
            resultList.add(map);
        }

        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("total",pageInfo.getTotal());
        dataMap.put("rows", resultList);
        //服务端分页，返回的结果必须包含total、rows两个参数。漏写或错写都会导致表格无法显示数据。
        return R.ok(dataMap);
    }

    /**
     * 获取登录的用户信息
     */
    @RequestMapping(value = "/loginUserInfo")
    public R loginUserInfo(){
        return R.ok(getCurrLoginUser());
    }

    /**
     * 修改登录用户密码
     */
    @LogRecord(operation="修改密码",remark = "修改登录用户密码",moduleName = "用户管理")
    @PostMapping(value = "/password")
    public R password(String password,String newPassword){
        if(StringUtils.isBlank(newPassword)){
            return R.fail("新密码不为能空");
        }
        //更新密码
        int count = sysUserService.updatePassword(getLoginUserId(), password, newPassword);
        if(count == 0){
            return R.fail("原密码不正确");
        }
        return R.ok();
    }

    /**
     * 根据用户ID获取用户信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/info")
    public R info(Long id) {
        SysUser user = sysUserService.selectByPrimaryKey(id);
        if(user == null){
            return R.ok();
        }
        SysUserExt sysUserExt = new SysUserExt();
        try {
            BeanUtils.copyProperties(sysUserExt,user);
        } catch (IllegalAccessException e) {
            logger.error(e.getMessage(),e);
        } catch (InvocationTargetException e) {
            logger.error(e.getMessage(), e);
        }
        //获取用户所属的角色列表
        SysUserRoleExample sysUserRoleExample = new SysUserRoleExample();
        sysUserRoleExample.createCriteria().andUserIdEqualTo(id);
        List<SysUserRole> sysUserRoleList = sysUserRoleService.selectByExample(sysUserRoleExample);
        if(CollectionUtils.isNotEmpty(sysUserRoleList)){
            List<Long> roleIdList = new ArrayList<>();
            for(SysUserRole userRole:sysUserRoleList){
                roleIdList.add(userRole.getRoleId());
            }
            sysUserExt.setRoleIdList(roleIdList);
        }
        return R.ok(sysUserExt);
    }

    /**
     * 更新系统用户
     * @param sysUser
     * @return
     */
    @LogRecord(operation="修改用户",remark = "修改系统用户",moduleName = "用户管理")//使用自定义的LogRecord注解记录操作日志
    @PostMapping(value = "/update")
    public R update(SysUserExt sysUser){
        if(StringUtils.isBlank(sysUser.getUsername())){
            return R.fail("用户名不能为空");
        }
        sysUser.setUpdateUser(getLoginUserId());
        sysUserService.update(sysUser);
        return R.ok();
    }

    /**
     * 根据用户id批量删除用户
     * @param ids 要删除的用户ID，以逗号分隔
     * @return
     */
    @LogRecord(operation="删除用户",remark = "根据用户id删除用户",moduleName = "用户管理")
    @RequestMapping(value = "/delete")
    public R delete(String ids){
        List<Long> idList = new ArrayList<>();
        if(StringUtils.isNotEmpty(ids)){
            String[] idArr = ids.split(",");
            for(String id:idArr){
                idList.add(Long.parseLong(id));
            }
        }
        if(idList.contains(getLoginUserId())){
            return R.fail("当前登录用户不能删除");
        }
        //根据用户id删除
        sysUserService.delete(getLoginUserId(),idList);
        return R.ok();
    }

    /**
     * 根据用户id批量禁用用户
     * @param ids 要操作的用户ID，以逗号分隔
     * @return
     */
    @LogRecord(operation="禁用用户",remark = "根据用户id禁用用户",moduleName = "用户管理")
    @RequestMapping(value = "/forbid")
    public R forbid(String ids){
        List<Long> idList = new ArrayList<>();
        if(StringUtils.isNotEmpty(ids)){
            String[] idArr = ids.split(",");
            for(String id:idArr){
                idList.add(Long.parseLong(id));
            }
        }
        if(idList.contains(getLoginUserId())){
            return R.fail("当前登录用户不能禁用");
        }
        sysUserService.forbid(getLoginUserId(),idList);
        return R.ok();
    }

    /**
     * 根据用户id批量启用用户
     * @param ids 要操作的用户ID，以逗号分隔
     * @return
     */
    @LogRecord(operation="启用用户",remark = "根据用户id启用用户",moduleName = "用户管理")
    @RequestMapping(value = "/enable")
    public R enable(String ids){
        List<Long> idList = new ArrayList<>();
        if(StringUtils.isNotEmpty(ids)){
            String[] idArr = ids.split(",");
            for(String id:idArr){
                idList.add(Long.parseLong(id));
            }
        }
        sysUserService.enable(getLoginUserId(),idList);
        return R.ok();
    }

    /**
     * 重置用户密码
     * @param id 用户ID
     * @param newPassword 新密码
     * @return
     */
    @LogRecord(operation="重置密码",remark = "重置用户密码",moduleName = "用户管理")
    @RequestMapping(value = "/resetPwd")
    public R resetPwd(Long id,String newPassword){
        sysUserService.resetPwd(getLoginUserId(),id,newPassword);
        return R.ok();
    }

    /**
     * 修改密码
     * @param nowPassword
     * @param newPassword
     * @return
     */
    @LogRecord(operation="修改密码",remark = "用户修改密码",moduleName = "用户管理")
    @RequestMapping(value = "/updatePwd")
    public R updatePwd(String nowPassword,String newPassword){
        sysUserService.updatePwd(getLoginUserId(),nowPassword,newPassword);
        return R.ok();
    }

    @LogRecord(operation="修改个人信息",remark = "用户修改个人信息",moduleName = "用户管理")
    @RequestMapping(value = "/updateUserInfo")
    public R updateUserInfo(SysUser sysUser){
        sysUser.setId(getLoginUserId());
        sysUserService.updateUserInfo(sysUser);
        return R.ok();
    }
}
